import './App.css';
import React, { Component } from 'react'

export default class App extends Component {
  state = {
    count: 2,
    arr: [1, 3, 2, 4]
  }

  changeA = () => {
    this.setArr();
  }

  setArr = () => {
    const { count } = this.state
    const newMax = count * count;
    let newArr = new Array(newMax);
    for (let i = 0; i < newMax; i++) {
      newArr[i] = i + 1
    }
    let reArr = new Array(newMax);
    for (let i = 0; i < newMax; i++) {
      let n = Math.ceil(Math.random(0, 1) * (newArr.length)) - 1;
      reArr[i] = newArr[n];
      newArr = newArr.filter((value) => {
        return value !== reArr[i];
      })
    }
    this.setState({ arr: reArr })
  }

  changeInput = (e) => {
    if ((e.keyCode >= 48 && e.keyCode <= 57) || e.keyCode === 13 || e.keyCode === 8 || (e.keyCode >= 96 && e.keyCode <= 105)) {
      if (e.keyCode === 13) {
        if (e.target.value >= 2 && e.target.value <= 10) {
          this.setState({ count: e.target.value }, () => {
            this.setArr();
          });
          e.target.value = '';
        } else {
          alert("输入错误，请重新输入！");
          e.target.value = '';
        }
      }
    } else {
      alert("输入错误，请重新输入！");
      e.target.value = '';
    }
  }

  changeColor = () => {

  }

  render() {
    const { count, arr } = this.state
    return (
      <div className="App">
        <div className="all">
          <div className="game" style={{ width: (count * 24) + 'px', height: (count * 24) + 'px' }}>
            {arr.map((value, index) => {
              return <div className="item" key={index} style={{ width: '18px', height: '18px', fontSize: "15px" }} onClick={this.changeColor}>{value}</div>
            })}
          </div>
          <div style={{ fontSize: "12px" }}>输入难度2~10,按回车确认</div>
          <div className="footer">
            <input type="text" placeholder="默认2" style={{ width: '40px' }} onKeyDown={this.changeInput} />
            <button onClick={this.changeA}>刷新</button>
          </div>
        </div>
      </div>
    );
  }
}
